<template>
  <ebook-dialog :title="title" ref="dialog">
    <!-- 原列表 -->
    <div class="dialog-list-wrapper" v-if="!ifNewGroup">
      <div v-for="(item, index) in categoryList" :key="index">
        <div
          class="dialog-list-item"
          :class="{ 'is-add': item.edit ? item.edit === 1 : false }"
          @click="onGroupClick(item)"
          v-if="(item.edit === 2 && isInGroup) || item.edit !== 2 || !item.edit"
        >
          <div class="dialog-list-item-text">{{ item.title }}</div>
          <div
            class="dialog-list-icon-wrapper"
            v-if="item.title === shelfCategory.title"
          >
            <span class="icon-check"></span>
          </div>
        </div>
      </div>
    </div>
    <!-- 新列表 -->
    <div class="dialog-new-group-wrapper" v-else>
      <div class="dialog-input-title-wrapper">
        <span class="dialog-input-title">{{ $t('shelf.groupName') }}</span>
      </div>
      <div class="dialog-input-wrapper">
        <div class="dialog-input-inner-wrapper">
          <input
            type="text"
            class="dialog-input"
            v-model="newGroupName"
            ref="dialogInput"
          />
          <div
            class="dialog-input-clear-wrapper"
            @click="clear"
            v-show="newGroupName && newGroupName.length > 0"
          >
            <span class="icon-close-circle-fill"></span>
          </div>
        </div>
      </div>
    </div>
    <div slot="btn" class="group-dialog-btn-wrapper">
      <div class="dialog-btn" @click="hide">{{ $t('shelf.cancel') }}</div>
      <div
        class="dialog-btn"
        @click="createNewGroup"
        :class="{ 'is-empty': newGroupName && newGroupName.length === 0 }"
        v-if="ifNewGroup"
      >
        {{ $t('shelf.confirm') }}
      </div>
    </div>
  </ebook-dialog>
</template>

<script>
import EbookDialog from '../common/Dialog.vue'
import { storeShelfMixin } from '../../utils/mixin'
import { removeAddFromShelf, appendAddToshelf, computedId } from '../../utils/store'
import { saveBookShelf } from '../../utils/localStorage'
export default {
  name: 'group-dialog',
  mixins: [storeShelfMixin],
  components: {
    EbookDialog
  },
  props: {
    showNewGroup: {
      type: Boolean,
      default: false // 默认时打开列表而不是打开新建
    },
    groupName: String
  },
  computed: {
    defaultCategory() {
      return [
        {
          title: this.$t('shelf.newGroup'),
          edit: 1
        },
        {
          title: this.$t('shelf.groupOut'),
          edit: 2
        }
      ]
    },
    category() {
      return this.shelfList.filter((item) => item.type === 2)
    },
    categoryList() {
      return [...this.defaultCategory, ...this.category]
    },
    title() {
      return !this.ifNewGroup
        ? this.$t('shelf.moveBook')
        : this.$t('shelf.newGroup')
    },
    isInGroup() {
      return this.currentType === 2
    }
  },
  data() {
    return {
      ifNewGroup: false,
      newGroupName: '',
      list: null
    }
  },
  methods: {
    show() {
      this.ifNewGroup = this.showNewGroup
      // this.newGroupName = this.groupName
      console.log(this.ifNewGroup)
      console.log(this.newGroupName)
      this.$refs.dialog.show()
    },
    hide() {
      this.$refs.dialog.hide()
      // 解决修改分组名完成后 动画出现短暂的重叠
      setTimeout(() => {
        this.ifNewGroup = false
      }, 200)
    },
    onGroupClick(item) {
      if (item.edit && item.edit === 1) {
        this.ifNewGroup = true
      } else if (item.edit && item.edit === 2) {
        this.moveOutFromGroup()
      } else {
        this.moveToGroup(item)
      }
    },
    clear() {
      this.newGroupName = ''
    },
    moveToGroup(group) {
      this.setShelfList(
        // 去除掉选中的数组
        this.shelfList.filter((book) => {
          if (book.itemList) {
            book.itemList = book.itemList.filter(
              (subBook) => this.shelfSelected.indexOf(subBook) < 0
            )
          }
          return this.shelfSelected.indexOf(book) < 0
        })
      ).then(() => {
        // 将选中的数组和 itemList 合并
        if (group && group.itemList) {
          group.itemList = [...group.itemList, ...this.shelfSelected]
        }
        // 保持id的顺序
        group.itemList.forEach((item, index) => {
          item.id = index + 1
        })
        this.simpleToast(
          this.$t('shelf.moveBookInSuccess').replace('$1', group.title)
        )
        this.onComplete()
      })
    },
    // 移除分组功能
    moveOutFromGroup() {
      // 1 将选中的电子书移出  shelfCategory
      this.shelfSelected.forEach(selected => {
        this.shelfList.filter(list => {
          if (list.itemList) {
            list.itemList = list.itemList.filter(itemlists => itemlists.id !== selected.id)
          }
          return list
        })
      })
      this.setShelfList(
        this.shelfList
      ).then(() => {
        // 解决移除分组后页面没有立即渲染
        this.shelfSelected.forEach(item => {
          this.shelfCategory.itemList = this.shelfCategory.itemList.filter(category => category !== item)
        })
        // this.setShelfList(this.shelfList)
        // saveBookShelf(this.shelfList)
        // 将shelfList 中的 最后一个加号去掉
        // 合并数组
        // 将加号追加上
        /**
         * 这里还有很重要的步骤是去重新计算id
         * 因为我们的书架图书的顺序被改变了
         * 改变后要去重新计算id
         * 因为我们既有改动分组里面的数据也改动外面的数据
         * store.js 中定义方法 */
        const list = computedId(appendAddToshelf([].concat(removeAddFromShelf(this.shelfList), ...this.shelfSelected)))
        this.setShelfList(list).then(() => {
          this.simpleToast(this.$t('shelf.moveBookOutSuccess'))
          this.onComplete()
        })
      })
    },
    createNewGroup() {
      // 待优化
      // 判断是否为空
      if (!this.newGroupName || this.newGroupName.length === 0) {
        return
      }
      // 修改分组名情况
      if (this.showNewGroup) {
        this.shelfList.forEach(item => {
          if (item.itemList && item.title === this.shelfCategory.title) {
            item.title = this.newGroupName
          }
        })
        this.shelfCategory.title = this.newGroupName
        this.onComplete()
      } else {
      // 新建分组对象
        const group = {
        // id 为 书架中倒数第二个元素的id + 1 因为最后一个元素是个加号
          id: this.shelfList[this.shelfList.length - 2].id + 1,
          itemList: [],
          selected: false,
          title: this.newGroupName,
          type: 2
        }
        // 排除加号
        const list = removeAddFromShelf(this.shelfList)
        list.push(group)
        // 当选中图书时 点击新建分组 将图书一并加入
        if (this.shelfSelected) {
          this.shelfSelected.forEach((item) => {
            list[list.length - 1].itemList.push(item)
            // this.setShelfList(this.shelfList.filter((list) => list !== item))
          })
        }
        // 追加加号
        this.setShelfList(appendAddToshelf(list)).then(() => {
          this.shelfSelected.forEach((item) => {
            this.setShelfList(this.shelfList.filter((list) => list !== item))
          })
          this.onComplete()
        })
      }
    },
    onComplete() {
      saveBookShelf(this.shelfList)
      console.log(this.shelfList)
      this.setIsEditMode(false)
      this.hide()
    }
  }
}
</script>

<style lang="scss" rel="stylesheet/scss" scoped>
@import '../../assets/style/global';

.dialog-list-wrapper {
  width: 100%;
  padding: 0 px2rem(20);
  box-sizing: border-box;
  font-size: px2rem(14);
  @include scroll;
  .dialog-list-item {
    display: flex;
    padding: px2rem(15) 0;
    box-sizing: border-box;
    color: #666;
    &.is-add {
      color: $color-blue;
      &:active {
        color: $color-blue-transparent;
      }
    }
    &:active {
      color: rgba(102, 102, 102, 0.5);
    }
    .dialog-list-item-text {
      flex: 1;
    }
    .dialog-list-icon-wrapper {
      flex: 0 0 px2rem(30);
      color: $color-blue;
      @include right;
    }
  }
}

.dialog-new-group-wrapper {
  width: 100%;
  padding: 0 px2rem(20);
  box-sizing: border-box;
  .dialog-input-title-wrapper {
    font-size: px2rem(10);
    margin-top: px2rem(20);
  }
  .dialog-input-wrapper {
    width: 100%;
    padding: 0 0 px2rem(30) 0;
    box-sizing: border-box;
    .dialog-input-inner-wrapper {
      display: flex;
      width: 100%;
      padding: px2rem(10) 0;
      box-sizing: border-box;
      border-bottom: px2rem(1) solid #eee;
      font-size: px2rem(14);
      color: #666;
      .dialog-input {
        flex: 1;
        border: none;
        &:focus {
          outline: none;
        }
      }
      .dialog-input-clear-wrapper {
        flex: 0 0 px2rem(30);
        color: #ccc;
        @include center;
        &:active {
          color: #999;
        }
      }
    }
  }
}

.group-dialog-btn-wrapper {
  width: 100%;
  @include center;
}
.dialog-btn {
  flex: 1;
  &.is-empty {
    color: rgba(255, 255, 255, 0.5);
  }
  &:active {
    color: rgba(255, 255, 255, 0.5);
  }
}
</style>
